import React, { useState, useCallback, useLayoutEffect } from 'react'
import { View, Image, ScrollView } from '@tarojs/components'
import Images from '@ASSET/Images'
import style from './TabWIthMoreButton.module.scss'

const ALL = 'all'

export default function TabWithMoreButton({
  tabs = [], initialIndex = 0, showMore, language, onTabChange, onClickMore, showTag
}) {
  const [activeIndex, setActiveIndex] = useState(initialIndex)
  const [scrollToId, setScrollId] = useState(ALL)

  useLayoutEffect(() => {
    const id = `tab${initialIndex ? initialIndex - 1 : 0}`
    setActiveIndex(initialIndex)
    setScrollId(id)
  }, [initialIndex, tabs])

  const onClickItem = useCallback((i, tagData) => {
    setActiveIndex(i)
    onTabChange(tagData, i)
    const scrollIndex = i ? i - 1 : 0
    setScrollId(`tab${scrollIndex}`)
  }, [onTabChange])

  if (!showTag) return null

  return (
    <View className={style.container}>
      <ScrollView
        className={`${style.tabView} ${showMore ? style.showMoreList : ''}`}
        scrollX
        scrollIntoView={scrollToId}
      >
        <View
          id="tab0"
          key={ALL}
          onClick={() => { onClickItem(0, tabs[0]) }}
          className={`${style.tabItem} ${!activeIndex ? style.active : ''}`}
        >
          <View className={style.tabItemContent}>
            {tabs[0]?.Title?.[language]}
            {!activeIndex && <View className={style.indicate} />}
          </View>
        </View>
        <View className={style.otherTab}>
          {tabs.slice(1).map((item = {}, index) => {
            const { Title, p8Id } = item
            const actualIndex = index + 1
            const active = actualIndex === activeIndex
            const key = p8Id || ALL
            return (
              <View
                id={`tab${actualIndex}`}
                key={key}
                onClick={() => { onClickItem(actualIndex, item, key) }}
                className={`${style.tabItem} ${active ? style.active : ''}`}
              >
                <View className={style.tabItemContent}>
                  {Title?.[language]}
                  {active && <View className={style.indicate} />}
                </View>
              </View>
            )
          })}
        </View>
      </ScrollView>
      {!!showMore && (
        <View className={style.moreBtn} onClick={onClickMore}>
          <Image src={Images.video.pull_down} className={style.moreIcon} />
        </View>
      )}
    </View>
  )
}
